<template>
  <div class="container">
    <el-dialog
      :title="
        dialog.dialogType === 'edit' ? '修改商超订货单' : '创建商超订货单'
      "
      :visible.sync="dialog.centerDialogVisible"
      width="1400px"
      center
      :lock-scroll="true"
      :before-close="hideDialog"
      @open="getData"
      @close="hideDialog"
    >
      <div class="top">
        <el-form label-width="130px" label-position="left">
          <el-form-item label="供应商：">
            <el-select
              v-model="inside.value"
              :multiple="false"
              filterable
              remote
              center
              reserve-keyword
              placeholder="请选择供应商"
              :remote-method="insideRemoteMethod"
              :loading="inside.loading"
              @change="getOptionId(inside.value)"
            >
              <el-option
                v-for="item in inside.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="采购员：">
            <el-select
              v-model="purchase.value"
              :disabled="purchase.type"
              :multiple="false"
              filterable
              remote
              center
              reserve-keyword
              placeholder="请选择采购员"
              :remote-method="insidePurchaseMethod"
              :loading="inside.loading"
              @change="getPurchase(purchase.value)"
            >
              <el-option
                v-for="item in purchase.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配送中心：">
            <el-select
              :multiple="false"
              filterable
              remote
              center
              reserve-keyword
              v-model="selectList"
              placeholder="请搜索选择配送中心"
              @change="distribution(selectList)"
              :remote-method="selectListsRemoteMethod"
              :loading="selectLists.loading"
            >
              <el-option
                v-for="item in selectLists.option"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="预计到货时间：">
            <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="formData.pre_time"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="入库状态：">
            <el-switch
              v-model="formData.is_avg"
              active-text="平均价入库"
              inactive-text="成本价入库"
            >
            </el-switch>
          </el-form-item>
        </el-form>
        <el-form
          style="margin-left: 40px"
          label-width="130px"
          label-position="left"
        >
          <el-form-item label="司机电话：">
            <el-input
              style="width: 220px"
              v-model="formData.driver_phone"
              placeholder="请输入司机电话"
            ></el-input>
          </el-form-item>
          <el-form-item label="车牌号：">
            <el-input
              style="width: 220px"
              v-model="formData.car_number"
              placeholder="请输入车牌号"
            ></el-input>
          </el-form-item>
          <el-form-item label="接收人：">
            <el-input
              style="width: 220px"
              v-model="formData.receive_people"
              placeholder="请输入接收人"
            ></el-input>
          </el-form-item>
          <el-form-item label="运费：">
            <el-input
              style="width: 220px"
              v-model="formData.freight_fee"
              placeholder="请输入运费"
            ></el-input>
          </el-form-item>
          <el-form-item label="付款方式：">
            <el-switch
              v-model="formData.fee_way"
              active-text="到付"
              inactive-text="预付"
            >
            </el-switch>
          </el-form-item>
        </el-form>
        <el-form
          style="margin-left: 40px"
          label-width="130px"
          label-position="left"
        >
          <el-form-item label="发货人：">
            <el-input
              style="width: 220px"
              v-model="formData.send_people"
              placeholder="请输入发货人"
            ></el-input>
          </el-form-item>
          <el-form-item label="库管：">
            <el-input
              style="width: 220px"
              v-model="formData.warehouse_tube"
              placeholder="请输入库管"
            ></el-input>
          </el-form-item>
          <el-form-item label="质检：">
            <el-input
              style="width: 220px"
              v-model="formData.quality_inspection"
              placeholder="请输入质检"
            ></el-input>
          </el-form-item>
          <el-form-item label="附件：">
            <div class="annex">
              <el-upload
                class="upload-demo"
                style="display: inline; margin-left: 10px"
                action="#"
                :show-file-list="false"
                :http-request="addImg"
              >
                <el-button
                  size="mini"
                  type="primary"
                  class="handleSearch"
                  icon="el-icon-circle-plus"
                  >上传图片</el-button
                >
              </el-upload>
              <el-image
                style="
                  width: 115px;
                  height: 115px;
                  margin-left: 10px;
                  background: #eee;
                  text-align: center;
                  line-height: 115px;
                "
                :src="formData.imgUrl"
                fit="cover"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <el-form>
        <el-form-item label="商品：">
          <el-select
            size="small"
            v-model="commodity.value"
            :multiple="false"
            filterable
            remote
            center
            reserve-keyword
            placeholder="请选择商品"
            :remote-method="insideCommodityMethod"
            :loading="inside.loading"
          >
            <el-option
              v-for="item in commodity.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-button
            size="mini"
            type="primary"
            class="handleSearch"
            icon="el-icon-zoom-in"
            @click="add()"
            >添加</el-button
          >
          <el-button
            size="mini"
            type="primary"
            class="handleSearch"
            icon="el-icon-upload"
            @click="download()"
            >模板下载</el-button
          >

          <el-upload
            class="upload-demo"
            style="display: inline; margin-left: 10px"
            action="#"
            :show-file-list="false"
            :http-request="handleAvatarSuccess"
          >
            <el-button
              size="mini"
              type="primary"
              class="handleSearch"
              icon="el-icon-circle-plus"
              >导入商品</el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>

      <el-table
        :data="tableData"
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column
          prop="Name"
          label="商品名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="BarCode"
          label="条形码"
          width="150px"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="Unit"
          width="100px"
          label="单位"
          align="center"
        ></el-table-column>

        <el-table-column label="价格" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.price"
              @change="modificationPrice(scope)"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="数量" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @change="modificationNum(scope)"
              :controls="false"
              v-model="scope.row.num"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="SonCounts" label="入库规格" align="center">
          <template slot-scope="scope">
            <div v-if="dialog.dialogType === 'edit'">
              {{ scope.row.rk_spec }}
            </div>
            <el-select
              v-else
              v-model="scope.row.rk_spec"
              @change="sonCount(scope)"
              placeholder="请选择"
            >
              <el-option
                v-for="item in scope.row.SonCountsList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column
          prop="qty"
          width="100px"
          label="件数"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="total"
          width="100px"
          label="总金额"
          align="center"
        ></el-table-column>
        <el-table-column label="生产日期" align="center" width="250px">
          <template slot-scope="scope">
            <el-date-picker
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="scope.row.produce_date"
              type="datetime"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="保质期（天）" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.shelf_life"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-delete"
              type="danger"
              @click="handleDelete(scope)"
              >删除</el-button
            >
            <el-button
              v-if="dialog.dialogType != 'edit'"
              size="mini"
              type="primary"
              class="handleSearch"
              icon="el-icon-circle-plus"
              @click="addSpec(scope)"
              >添加规格</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        width="400px"
        title="添加规格"
        center
        :visible.sync="spaceDialog"
        append-to-body
        @close="cancelSpec"
      >
        <el-form label-width="100px" label-position="center">
          <el-form-item label="规格：">
            <el-input-number
              size="small"
              :controls="false"
              v-model="spec"
            ></el-input-number>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelSpec">取 消</el-button>
          <el-button type="primary" @click="specNum()">确 定</el-button>
        </span>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { Loading } from "element-ui";
import { selectSupplierData } from "@/api/supplier/supplierList"; //供应商
// import { supplierList } from "@/api/supplier/supplierList";
import {
  // selectBuyerList,
  selectErpGoodsList,
  addBuyOrder,
  getBuyOrderGoods,
  // selectSupplierList,
  editBuyOrder,
  findAdminInfoUncheck,
  importBuyOrderGoods,
} from "@/api/putStorage/superPurchaseList";
import {
  getPrepurchaseGoods,
  editPrepurchase,
  addPrepurchase,
} from "@/api/superIndent/superIndentList";
import { getList } from "@/api/putStorage/putStotageList"; //采购员
// import { getSupplierBindGoods } from "@/api/commodity/commodityList"; //商品
import { selectErpGoodsData } from "@/api/commodity/commodityList"; //商品
import { selectRdcData } from "@/api/select/select";
export default {
  props: {
    dialog: Object,
    dialogData: Object,
  },
  data() {
    return {
      formData: {
        supplier_id: "",
        supplier_code: "",
        supplier_name: "",
        goods: "",
        buyer_id: "",
        buyer_code: "",
        buyer_name: "",
        is_avg: false,
        pre_time: "",
        send_people: "",
        driver_phone: "",
        car_number: "",
        receive_people: "",
        freight_fee: "",
        fee_way: false,
        warehouse_tube: "",
        quality_inspection: "",
        annex: "",
        imgUrl: "",
      },
      inside: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
      },
      selectLists: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      },
      selectList: "",
      purchase: {
        innerVisible: false,
        options: [],
        value: "",
        type: false,
        list: [],
        loading: false,
      },
      commodity: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
      },
      tableData: [],
      commodityList: [],
      spaceDialog: false,
      spec: "0",
      specId: "",
      search: {
        selectnamecode: "",
      },
      distributionData: {
        name: "",
        code: "",
      },
    };
  },
  methods: {
    //获取修改数据
    getData() {
      let data = {
        page: 1,
        limit: 100,
      };
      //是不是采购员
      findAdminInfoUncheck().then((res) => {
        if (res.data.admin_info.acc_type == 3) {
          this.purchase.value = res.data.admin_info.buyer;
          this.purchase.type = true;
        } else {
          this.purchase.type = false;
        }
      });
      //获取供应商列表
      selectSupplierData(data).then((res) => {
        this.inside.options = res.data.paginate.data.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.supplier_name}`,
            code: `${item.supplier_code}`,
          };
        });
      });
      //获取商超采购员列表
      getList(data).then((res) => {
        this.purchase.options = res.data.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.name}(${item.code})`,
            code: `${item.code}`,
          };
        });
      });
      //获取商品
      this.getDatas();
      console.log(this.dialogData, 8888);
      if (this.dialog.dialogType == "edit") {
        this.inside.value = this.dialogData.supplier_name;
         this.formData.supplier_name = this.dialogData.supplier_name;
        this.formData.supplier_id = this.dialogData.supplier_id;
        this.formData.supplier_code = this.dialogData.supplier_code;
        this.purchase.value =
          this.dialogData.buyer_name + "(" + this.dialogData.buyer_code + ")";
        this.formData.buyer_name =
          this.dialogData.buyer_name + "(" + this.dialogData.buyer_code + ")";
        this.formData.buyer_id = this.dialogData.buyer_id;
        this.formData.buyer_code = this.dialogData.buyer_code;
        this.distributionData = {
          name: this.dialogData.dcname,
          code: this.dialogData.dccode,
        };
        this.formData.is_avg = this.dialogData.is_avg;
        this.formData.pre_time = this.dialogData.pre_time;
        this.formData.send_people = this.dialogData.send_people;
        this.formData.driver_phone = this.dialogData.driver_phone;
        this.formData.car_number = this.dialogData.car_number;
        this.formData.receive_people = this.dialogData.receive_people;
        this.formData.freight_fee = this.dialogData.freight_fee;
        this.formData.fee_way = this.dialogData.fee_way;
        this.formData.warehouse_tube = this.dialogData.warehouse_tube;
        this.formData.quality_inspection = this.dialogData.quality_inspection;
        this.formData.annex = this.dialogData.annex;
        this.formData.imgUrl = this.imgHttp + this.dialogData.annex;
        this.selectList = this.dialogData.dcname;
        let datas = {
          id: this.dialog.id,
        };
        getPrepurchaseGoods(datas).then((res) => {
          if (res.code == 0) {
            res.data.goodslist.forEach((item) => {
              this.tableData.push({
                price: item.price,
                num: item.count,
                qty: item.bos_qty,
                Name: item.name,
                Spec: item.spec,
                Code: item.goods_code,
                ProductId: item.goods_erp_id,
                Unit: item.unit,
                ClassCode: item.category_code,
                ClassName: item.category_name,
                BarCode: item.goods_bar_code,
                produce_date: item.produce_date,
                shelf_life: item.shelf_life,
                id: item.id,
                total:
                  item.price != 0 && parseFloat(item.count) != 0
                    ? (item.price * parseFloat(item.count)).toFixed(4)
                    : 0,
                rk_spec: item.rk_spec,
              });
            });
          }
        });
      }
      this.getselsetData();
    },
    getselsetData() {
      let data = {
        page: 1,
        limit: 500,
        code_or_name: this.search.selectnamecode,
      };
      //获取配送中心
      selectRdcData(data).then((res) => {
        if (res.data.paginate.data) {
          this.selectLists.option = res.data.paginate.data.map((item) => {
            return { value: `${item.d_code}`, label: `${item.d_name}` };
          });
        }
      });
    },
    // 嵌套搜索配送方式数据
    selectListsRemoteMethod(query) {
      if (query !== "") {
        this.houseList(query);
      } else {
        this.selectLists.option = [];
      }
    },
    //获取配送数据
    houseList(query) {
      this.search.selectnamecode = query;
      this.getselsetData();
    },
    getDatas() {
      let data = {
        goods_code: "",
        // supplier_code: this.formData.supplier_code,
        page: 1,
        limit: 100,
      };
      //获取商超商品列表
      selectErpGoodsData(data).then((res) => {
        this.commodityList = res.data.paginate.data;
        this.commodity.options = res.data.paginate.data.map((item) => {
          return { value: `${item.Code}`, label: `${item.Name}` };
        });
      });
    },
    //获取供应商数据
    getSupplierList(query) {
      let data = {
        name: query,
        page: 1,
        limit: 100,
      };
      this.inside.loading = true;
      selectSupplierData(data).then((res) => {
        this.inside.list = res.data.paginate.data.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.supplier_name}`,
            code: `${item.supplier_code}`,
          };
        });
        this.inside.loading = false;
        this.inside.options = this.inside.list.filter((item) => {
          return (
            item.label.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
            item.code.toLowerCase().indexOf(query.toLowerCase()) > -1
          );
        });
      });
    },
    // 嵌套搜索供应商数据
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getSupplierList(query);
      } else {
        this.inside.options = [];
      }
    },
    //选择供应商获取ID
    getOptionId(e) {
      let data = this.inside.options.filter((res) => {
        return res.value == this.inside.value;
      });
      this.formData.supplier_id = data[0].value;
      this.formData.supplier_code = data[0].code;
      this.formData.supplier_name = data[0].label;
    },
    // 嵌套搜索采购员数据
    insidePurchaseMethod(query) {
      if (query !== "") {
        this.getPurchaseList(query);
      } else {
        this.purchase.options = [];
      }
    },
    getPurchaseList(query) {
      let data = {
        key: query,
        page: 1,
        limit: 100,
      };
      this.purchase.loading = true;
      getList(data).then((res) => {
        this.purchase.list = res.data.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.name}(${item.code})`,
            code: `${item.code}`,
          };
        });
        this.purchase.loading = false;
        this.purchase.options = this.purchase.list.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      });
    },
    getPurchase(e) {
      let data = this.purchase.options.filter((res) => {
        return res.value == e;
      });
      this.formData.buyer_id = data[0].value;
      this.formData.buyer_code = data[0].code;
      this.formData.buyer_name = data[0].label;
    },
    // 嵌套搜索商品数据
    insideCommodityMethod(query) {
      if (query !== "") {
        this.getCommodityList(query);
      } else {
        this.commodity.options = [];
      }
    },
    getCommodityList(query) {
      let data = {
        goods_code: query,
        page: 1,
        limit: 100,
      };
      this.purchase.loading = true;
      selectErpGoodsData(data).then((res) => {
        this.commodityList = res.data.paginate.data;
        this.commodity.options = res.data.paginate.data.map((item) => {
          return { value: `${item.Code}`, label: `${item.Name}` };
        });
        this.commodity.loading = false;
      });
    },
    hideDialog() {
      this.dialog.centerDialogVisible = false;
      this.formData = {
        supplier_id: "",
        supplier_code: "",
        supplier_name: "",
        goods: "",
        buyer_id: "",
        buyer_code: "",
        buyer_name: "",
        is_avg: false,
        pre_time: "",
        send_people: "",
        driver_phone: "",
        car_number: "",
        receive_people: "",
        freight_fee: "",
        fee_way: false,
        warehouse_tube: "",
        quality_inspection: "",
        annex: "",
        imgUrl: "",
      };

      this.inside = {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
      };
      this.purchase = {
        innerVisible: false,
        options: [],
        value: "",
        type: false,
        list: [],
        loading: false,
      };
      this.commodity = {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
      };
      (this.selectLists = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      }),
        (this.selectList = "");
      this.tableData = [];
      this.commodityList = [];
      this.distributionData = {
        name: "",
        code: "",
      };
    },
    //添加规格
    addSpec(scope) {
      this.specId = scope.row.BarCode;
      this.spaceDialog = true;
    },
    cancelSpec() {
      this.spaceDialog = false;
      this.spec = 0;
      this.specId = "";
    },
    //规格确定
    specNum() {
      this.tableData.forEach((res, index) => {
        if (res.BarCode == this.specId) {
          res.SonCountsList.push({
            value: this.spec,
            label: this.spec,
          });
          this.$set(this.tableData, index, res);
          this.cancelSpec();
        }
      });
    },
    //商品添加
    add() {
      if (this.commodityList.length == 0) {
        this.$message({
          type: "info",
          message: "请选择商品",
        });
      } else {
        let data = this.commodityList.filter((res) => {
          return res.Code == this.commodity.value;
        });
        let bool = this.tableData.filter((res) => {
          return res.Code == data[0].Code;
        });
        if (bool.length > 0) {
          this.$message({
            type: "info",
            message: "该商品已添加",
          });
          return;
        } else {
          let sonArr = data[0].SonCounts.split(",");
          let sonObj = [];
          sonArr.forEach((res) => {
            if (res == 0) {
              sonObj.push({
                value: 1,
                label: 1,
              });
            } else {
              sonObj.push({
                value: res,
                label: res,
              });
            }
          });
          this.tableData.push({
            id: 0,
            price: data[0].SalePrice,
            num: 0,
            qty: 0,
            total: 0,
            produce_date: "",
            shelf_life: 0,
            rk_spec: sonObj[0].value,
            SonCountsList: sonObj,
            BarCode: data[0].BarCode,
            Name: data[0].Name,
            Spec: data[0].Spec,
            Code: data[0].Code,
            ProductId: data[0].ProductId,
            Unit: data[0].Unit,
            ClassCode: data[0].ClassCode,
            ClassName: data[0].ClassName,
            produce_date: data[0].produce_date,
          });
        }
      }
    },

    // 商品删除
    handleDelete(scope) {
      this.tableData.forEach((res, index) => {
        if (res.Code == scope.row.Code) {
          this.tableData.splice(index, 1);
        }
      });
    },

    //修改数量
    modificationNum(scope) {
      if (scope.row.num) {
        scope.row.total = (scope.row.price * scope.row.num).toFixed(4);
        if (scope.row.rk_spec == 0) {
          scope.row.qty = scope.row.num;
        } else {
          scope.row.qty = (
            scope.row.num / parseFloat(scope.row.rk_spec)
          ).toFixed(4);
        }

        this.$set(this.tableData, scope.$index, scope.row);
      } else {
        scope.row.total = 0;
        scope.row.qty = 0;
        this.$set(this.tableData, scope.$index, scope.row);
      }
    },
    //修改价格
    modificationPrice(scope) {
      if (scope.row.price) {
        scope.row.total = (scope.row.price * scope.row.num).toFixed(4);
      } else {
        scope.row.total = 0;
        this.$set(this.tableData, scope.$index, scope.row);
      }
    },
    //导入商品
    handleAvatarSuccess(param) {
      if (this.formData.supplier_code) {
        let loading = Loading.service({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.1)",
        });
        let data = new window.FormData();
        data.append("goods_file", param.file);
        data.append("token", getToken());
        data.append("supplier_code", this.formData.supplier_code);
        this.$axios
          .post("/smkapi/Prepurchase/importPrepurchaseGoods", data)
          .then((res) => {
            loading.close();
            if (res.data.code == 0) {
              this.$message({
                message: res.data.message || res.data.msg,
                type: "success",
              });
              if (res.data.data.length > 0) {
                this.tableData = [];
                res.data.data.forEach((result) => {
                  let sonArr = result.SonCounts.split(",");
                  let sonObj = [];
                  sonArr.forEach((res) => {
                    if (res == 0) {
                      sonObj.push({
                        value: 1,
                        label: 1,
                      });
                    } else {
                      sonObj.push({
                        value: res,
                        label: res,
                      });
                    }
                  });
                  result.price = result.zc_price || 0;
                  // result.numPrice = result.SalePrice || 0;
                  result.num = result.num || 0;
                  result.qty = result.bos_qty || 0;
                  result.total =
                    result.price != 0 && result.num != 0
                      ? (result.price * result.num).toFixed(4)
                      : 0;
                  result.rk_spec = result.selectSonCounts;
                  // result.is_avg = true
                  result.SonCountsList = sonObj;
                  this.tableData.push(result);
                });
              }
            } else {
              this.$message({
                type: "info",
                message: res.data.msg,
              });
            }
          });
      } else {
        this.$message({
          type: "info",
          message: "请选择供应商",
        });
      }
    },
    //上传附件
    addImg(param) {
      let loading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)",
      });
      let data = new window.FormData();
      data.append("filename", param.file);
      data.append("token", getToken());
      this.$axios.post("/smkapi/FileManage/upload", data).then((res) => {
        loading.close();
        if (res.data.code == 0) {
          this.formData.annex = res.data.data.file_path;
          this.formData.imgUrl = this.imgHttp + res.data.data.file_path;
          console.log(this.formData.annex);
        } else {
           this.$message({
            type: "info",
            message: res.data.msg,
          });
        }
      });
    },
    sonCount(scope) {
      if (scope.row.price && scope.row.num) {
        scope.row.total = (scope.row.price * scope.row.num).toFixed(4);
        if (scope.row.rk_spec == 0) {
          scope.row.qty = scope.row.num;
        } else {
          scope.row.qty = (
            scope.row.num / parseFloat(scope.row.rk_spec)
          ).toFixed(4);
        }

        this.$set(this.tableData, scope.$index, scope.row);
      } else {
        scope.row.total = 0;
        scope.row.qty = 0;
        this.$set(this.tableData, scope.$index, scope.row);
      }
    },
    download() {
      this.$confirm("是否下载模板?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let link = document.createElement("a");
          link.href =
            this.$axios.defaults.baseURL +
            "/smkapi/Prepurchase/downLoadPrepurchaseTmp?token=" +
            getToken();
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    distribution(code) {
      let arr = this.selectLists.option.filter((item) => {
        return item.value == code;
      });
      this.distributionData = {
        name: arr[0].label,
        code: arr[0].value,
      };
    },
    indexNum(str) {
      let firstNum = str.indexOf("(");
      return str.slice(0, firstNum);
    },
    //提交
    confirm() {
      if (this.formData.supplier_id == "") {
        this.$message({
          type: "info",
          message: "请选择供应商",
        });
      } else if (this.formData.buyer_id == "") {
        this.$message({
          type: "info",
          message: "请选择采购员",
        });
      } else if (this.distributionData.code == "") {
        this.$message({
          type: "info",
          message: "请选择配送中心",
        });
      } else if (this.tableData.length == 0) {
        this.$message({
          type: "info",
          message: "请选择商品",
        });
      } else {
        // return
        let table = [];
        this.tableData.forEach((res) => {
          table.push({
            id: res.id ? res.id : 0,
            goods_bar_code: res.BarCode,
            price: res.price,
            num: res.num,
            qty: res.qty,
            name: res.Name,
            spec: res.Spec,
            goods_code: res.Code,
            goods_erp_id: res.ProductId,
            unit: res.Unit,
            category_code: res.ClassCode,
            category_name: res.ClassName,
            rk_spec: res.rk_spec,
            produce_date: res.produce_date,
            shelf_life: res.shelf_life,
          });
        });
        let data = {
          supplier_id: this.formData.supplier_id,
          supplier_code: this.formData.supplier_code,
          supplier_name: this.formData.supplier_name,
          buyer_code: this.formData.buyer_code,
          buyer_name: this.indexNum(this.formData.buyer_name),
          buyer_id: this.formData.buyer_id,
          dccode: this.distributionData.code,
          dcname: this.distributionData.name,
          is_avg: this.formData.is_avg ? 1 : 0,
          pre_time: this.formData.pre_time,
          send_people: this.formData.send_people,
          driver_phone: this.formData.driver_phone,
          car_number: this.formData.car_number,
          receive_people: this.formData.receive_people,
          freight_fee: this.formData.freight_fee,
          fee_way: this.formData.fee_way ? 2 : 1,
          warehouse_tube: this.formData.warehouse_tube,
          quality_inspection: this.formData.quality_inspection,
          annex: this.formData.annex,

          goods: JSON.stringify(table),
        };
        // console.log(data);
        // return;
        if (this.dialog.dialogType == "edit") {
          data.id = this.dialog.id;
          editPrepurchase(data).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.msg || res.message,
              });
              this.$emit("upData");
              this.hideDialog();
            }
          });
        } else {
          addPrepurchase(data).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.msg || res.message,
              });
              this.$emit("upData");
              this.hideDialog();
            }
          });
        }
      }
    },
    //取消
    cancel() {
      this.hideDialog();
    },
  },
};
</script>
<style scoped>
.tab {
  display: flex;
}
.tab .el-form-item {
  flex: 1;
}
.top {
  display: flex;
}
.annex {
  display: flex;
}
</style>
